package com.hspedu.bot.service.impl.record;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hspedu.bot.mapper.RecordMapper;
import com.hspedu.bot.pojo.Bot;
import com.hspedu.bot.pojo.Record;
import com.hspedu.bot.pojo.User;
import com.hspedu.bot.service.record.RecordService;
import com.hspedu.bot.service.user.UserService;
import com.hspedu.bot.service.user.bot.BotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements RecordService {

    @Autowired
    private UserService userService;

    @Autowired
    private RecordService recordService;

    @Override
    public JSONObject getList(Integer page) {
        IPage<Record> botPage = new Page<>(page, 10);
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        List<Record> records = recordService.page(botPage, queryWrapper).getRecords();

        //将records提取有用信息后转换成JSONObject类型返回
        //信息[A的照片与名字、B的照片与名字、对局结果、时间]
        JSONObject resp = new JSONObject();
        List<JSONObject> items = new LinkedList<JSONObject>();
        for (Record record : records) {
            JSONObject item = new JSONObject();
            User userA = userService.getById(record.getAId());
            User userB = userService.getById(record.getBId());
            item.put("a_photo", userA.getPhoto());
            item.put("a_name", userA.getUsername());
            item.put("b_photo", userB.getPhoto());
            item.put("b_name", userB.getUsername());
            item.put("record", record);
            String result = "平局";
            if (record.getLoser().equals("A")) result = "B胜";
            else if (record.getLoser().equals("B")) result = "A胜";
            item.put("result", result);

            //添加这一条数据
            items.add(item);
        }
        resp.put("records", items);
        resp.put("records_total", recordService.count(null));       //对局总条数

        return resp;
    }
}
